package personresources.manager.dao.impl;

import java.io.Serializable;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;

import personresources.manager.dao.GenericDao;
/**
 * Implement of GenericDao
 * @author Duy Chuong
 *
 * @param <T> Class
 * @param <PK> Primary key
 */
public class GenericDaoImpl<T, PK extends Serializable> implements GenericDao<T, PK>  {

	private Class<T> type;
	HibernateTemplate hibernateTemplate;
	
	public GenericDaoImpl(Class<T> type){
		this.type = type;
	}
	
	@Autowired
	@Qualifier("sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	/**
	 * Get hibernateTemplate
	 * @return HibernateTemplate
	 */
	protected HibernateTemplate getHibernateTemplate(){
		return hibernateTemplate;
	}

	
	/**
	 * @see personresources.manager.dao.GenericDao#read(java.io.Serializable)
	 */
	public T read(PK key) {
		return (T) getHibernateTemplate().get(type, key);
	}

	/**
	 * @see personresources.manager.dao.GenericDao#create(java.lang.Object)
	 */
	public void create(T object) {
		this.getHibernateTemplate().save(object);
		
	}

	/**
	 * @see personresources.manager.dao.GenericDao#delete(java.lang.Object)
	 */
	public void delete(T object) {
		this.getHibernateTemplate().delete(object);
	}

	/**
	 * @see personresources.manager.dao.GenericDao#update(java.lang.Object)
	 */
	public void update(T object) {
		getHibernateTemplate().update(object);		
	}

	/**
	 * @see personresources.manager.dao.GenericDao#read(java.lang.String, java.lang.Object)
	 */
	public Object read(String property, Object value) {
		DetachedCriteria criteria = DetachedCriteria.forClass(type);
		criteria.add(Expression.eq(property,value));
		return getHibernateTemplate().findByCriteria(criteria).get(0);
	}
}
